package com.example.makerspace.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.example.makerspace.enums.ResultCodeEnum;
import com.example.makerspace.enums.UserRoleEnum;
import com.example.makerspace.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

import static com.example.makerspace.domain.UserDO.ROLE;

public class AdminAudiInterceptor  implements HandlerInterceptor{
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if(!JwtUtils.checkToken(token)){
            response.setHeader("Content-type", "text/html;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", ResultCodeEnum.UNSIGNED_USER.getCode());
            jsonObject.put("message", ResultCodeEnum.UNSIGNED_USER.getMessage());
            writer.write(jsonObject.toJSONString());
            return false;
        }
        Claims claims = JwtUtils.parseToken(token);
        Object role = claims.get(ROLE);
        if(!role.equals(UserRoleEnum.ADMIN.getRole()) && !role.equals(UserRoleEnum.Audit.getRole())){
            response.setHeader("Content-type", "text/html;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", ResultCodeEnum.IS_NOT_ADMIN.getCode());
            jsonObject.put("message", ResultCodeEnum.IS_NOT_ADMIN.getMessage());
            writer.write(jsonObject.toJSONString());
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

}
